/**
*      author: Y_Yao
*      created: 2025-01-04 20:24:16
**/

#include<bits/stdc++.h>

#define int LL
using namespace std;
using LL = long long;
const LL LLINF = 1e18;
const int INF = 0x3f3f3f3f;
const int N = 1000 + 7;
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,-1,1};
int h,w;
char a[N][N];
int f[N][N];//水平
int g[N][N];//竖值
bool vis[N][N];

void bfs(int sx,int sy)
{
    queue<pair<int,int>> q;
    q.push({sx,sy});
    vis[sx][sy] = true;

    while(!q.empty())
    {
        auto t = q.front();
        q.pop();
        int x = t.first,y = t.second;
        g[x][y] = min((x - 1) > 0 ? f[x - 1][y] : INF,(x + 1) <= h ? f[x + 1][y] : INF) + 1;
        f[x][y] = min((y - 1) > 0 ? g[x][y - 1] : INF,(y + 1) <= w ? g[x][y + 1] : INF) + 1;

        for(int i = 0;i < 4;i++)
        {
            int tx = x + dx[i],ty = y + dy[i];
            if(tx <= 0 || tx > h || ty <= 0 || ty > w) continue;
            if(vis[tx][ty]) continue;
            vis[tx][ty] = true;

            g[tx][ty] = min((tx - 1) > 0 ? f[tx - 1][ty] : INF,(tx + 1) <= h ? f[tx + 1][ty] : INF) + 1;
            f[tx][ty] = min((ty - 1) > 0 ? g[tx][ty - 1] : INF,(ty + 1) <= w ? g[tx][ty + 1] : INF) + 1;
            q.push({tx,ty}); 
        }
    }
}

void solve()
{
    memset(f,INF,sizeof f);
    memset(g,INF,sizeof g);
    cin >> h >> w;
    int sx,sy,ex,ey;
    for(int i = 1;i <= h;i++)
    {
        for(int j = 1;j <= w;j++)
        {
            cin >> a[i][j];
            if(a[i][j] == '#')
            {

            }
            if(a[i][j] == 'S')
            {
                sx = i,sy = j;
                f[i][j] = g[i][j] = 0;
            }
            if(a[i][j] == 'G')
            {
                ex = i,ey = j;
            }
        }
    }

    bfs(sx,sy);

    for(int i = 1;i <= h;i++)
    {
        for(int j = 1;j <= w;j++)
        {
            if(f[i][j] < 1000)
            cout << f[i][j] << " "; 
            else cout << "INF" << " ";
        }
        cout << endl;
    }
    cout << endl;
    for(int i = 1;i <= h;i++)
    {
        for(int j = 1;j <= w;j++)
        {
            if(g[i][j] < 1000)
            cout << g[i][j] << " "; 
            else cout << "INF" << " ";
        }
        cout << endl;
    }

    cout << min(f[ex][ey],g[ex][ey]) << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);

    int t = 1;
    //cin >> t;
    while(t--)
    {
        solve();
    }
    return 0;
}